using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;

namespace EasyXaf.EntityDesigner.Editors.CodeEditors;

public partial class CodeEditorRenderer
{
    private readonly string EditorId = $"id-{Guid.NewGuid()}";

    private DotNetObjectReference<CodeEditorRenderer> DotNetObjectRef { get; set; }

    private IJSObjectReference JsModule { get; set; }

    [Inject]
    private IJSRuntime JSRuntime { get; set; }

    [Parameter]
    public CodeEditorModel Model { get; set; }

    [JSInvokable]
    public Task SetCodeAsync(string code)
    {
        Model.RaiseCodeChanged(code);
        return Task.CompletedTask;
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            var jsModuleFile = "/Editors/CodeEditors/CodeEditorRenderer.razor.js";
            JsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", jsModuleFile);
            DotNetObjectRef = DotNetObjectReference.Create(this);
            await JsModule.InvokeVoidAsync("init", EditorId, DotNetObjectRef, new
            {
                mode = Model.Language,
                readOnly = Model.ReadOnly,
                rowCount = Model.RowCount,
            });
        }
    }
}